package com.dreamer.view.lottery;

import com.dreamer.domain.lottery.Prize;
import com.dreamer.service.lottery.PrizeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ps.mx.otter.utils.message.Message;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

@RestController
@RequestMapping("/prize")
public class PrizeController {

    @Autowired
    private PrizeHandler prizeHandler;

    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    public Message edit(@ModelAttribute("parameter") Prize prize) {
        try {
            prizeHandler.saveOrUpdate(prize);
            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage();
        }
    }

    @RequestMapping(value = "/remove.json", method = RequestMethod.DELETE)
    public Message remove(@ModelAttribute("parameter") Prize prize) {
        try {
            prizeHandler.removeActivity(prize);
            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage();
        }
    }

    @ModelAttribute("parameter")
    public Prize preprocess(@RequestParam("id") Optional<Integer> id) {
        Prize prize = new Prize();
        if (id.isPresent()) {
            prize = prizeHandler.findById(id.get());
        }
        return prize;
    }

}
